<template>
    <div class="content flex-col">
        <div class="tenant-header flex-row">
            <div class="tenant-header-left">
                用户管理
            </div>
            <div class="tenant-header-right">
                <a-button type="primary" @click="handleAdd">
                    <a-icon type="plus" />
                    添加用户
                </a-button>
            </div>
        </div>
        <div class="tenant-content tenant-table">
            <el-table
                    :data="users"
                    row-class-name="category-table-tr"
                    height="100%"
                    style="width: 100%">
                <el-table-column
                        prop="userName"
                        label="帐号">
                </el-table-column>
                <el-table-column
                        prop="userAlia"
                        label="用户名称">
                </el-table-column>
                <el-table-column
                        prop="userDeptNames"
                        label="部门">
                </el-table-column>
                <el-table-column
                        prop="userRole"
                        label="用户角色">
                    <template slot-scope="scope">
                        <el-select class="cgs-select"
                                   style="width: 160px; border: none !important;"
                                   v-model="scope.row.userRole"
                                   placeholder="选择分组"
                                   @change="handleChange($event,scope.row)"
                        >
                            <el-option v-for="role in role_options"
                                       :key="role.id"
                                       :value="role.id"
                                       :disabled="role.disabled"
                                       :label="role.roleName"
                            />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column>
                    <template slot="header" slot-scope="scope">
                        <el-input
                                v-model="searchInput"
                                size="mini"
                                style="width: 200px;"
                                placeholder="输入关键字搜索"/>
                    </template>
                    <template slot-scope="scope">
                        <el-button icon="el-icon-edit"
                                   @click="handleUpdate(scope.row)"
                                   type="text">修改</el-button>
                        <el-button icon="el-icon-delete"
                                   @click="handleDelete(scope.row)"
                                   type="text" style="color: red">删除</el-button>
                        <el-button @click="handleResetPassword(scope.row)"
                                   type="text" style="color: red">重置密码</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="tenant_floor">
            <el-pagination
                @size-change="pageSizeChange"
                @current-change="pageChange"
                :current-page="page.currentPage"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="submitState.state === 'add' ? '一 添加用户 一' : '一 修改用户信息 一'"
                   center
                   :visible.sync="dialogVisible"
                   @close="dialogVisible = false"
        >
            <el-form :model="form" :rules="formRules" ref="ruleForm" >
                <el-form-item label="帐 号："
                              v-if="submitState.state === 'add'"
                              :label-width="formLabelWidth"
                              prop="userName">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="密 码："
                              v-if="submitState.state === 'add'"
                              :label-width="formLabelWidth"
                              prop="userPassword">
                    <el-input v-model="form.userPassword"></el-input>
                </el-form-item>
                <el-form-item label="用户名称："
                              :label-width="formLabelWidth"
                              prop="userAlia">
                    <el-input v-model="form.userAlia"></el-input>
                </el-form-item>
                <el-form-item v-if="submitState.state === 'add'"
                              label="用户角色："
                              :label-width="formLabelWidth"
                              prop="userRole">
                    <el-select class="cgs-select"
                               style="width: 160px; border: none !important;"
                               v-model="form.userRole"
                               placeholder="选择分组"
                    >
                        <el-option v-for="role in role_options"
                                   :key="role.id"
                                   :value="role.id"
                                   :disabled="role.disabled"
                                   :label="role.roleName"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="部门："
                              :label-width="formLabelWidth"
                              prop="userDepts">
                    <el-cascader  v-model="form.userDepts"
                                  :options="dept_options"
                                  :props="{ checkStrictly: true }"
                    >
                    </el-cascader>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="formSubmit('ruleForm')">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {getUserList, addUser, deleteUser, editUser, getRoleList, resetUserPassword} from '@/api/authority'
    import {getDeptList,createDeptTree,createCascadDepValue} from '@/api/dept'
    export default {
        name: "user",
        data() {
            return {
                dialogVisible: false,
                role_options: [],
                dept_options: [],
                deptList: [],
                deptMaps:{},
                submitState: {
                    state:'add',
                    node: {}
                },
                page: {
                    pageSize: 10,
                    currentPage: 1
                },
                form: {
                    userName: '',
                    userAlia: '',
                    userPassword: '123456',
                    userRole: '',
                    userDepts:''
                },
                formRules: {
                    userName: [
                        { required: true, message: '请输入用户帐号', trigger: 'blur' },
                        { min: 2, message: '长度大于 2 个字符', trigger: 'blur' },
                        { validator: this.checkData, trigger: 'blur'}
                    ],
                    userPassword: [
                        { required: true, message: '请输入密码', trigger: 'blur' },
                        { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' },
                        { validator: this.checkData, trigger: 'blur'}
                    ],
                    userRole: [
                        { required: true, message: '请选择用户角色', trigger: 'change' }
                    ],
                    userAlia: [
                        { required: true, message: '请输入用户名称', trigger: 'blur' },
                    ],
                    userDepts: [
                        { required: true, message: '请选择部门', trigger: 'change' },
                    ],
                },
                formLabelWidth: '120px',
                searchInput: '',
                tableData: []
            }
        },
        computed:{
            users() {
                let {searchInput, tableData, page: {currentPage, pageSize}} = this;
                let filterData = tableData.filter(data => !searchInput || data.userName.toLowerCase().includes(searchInput.toLowerCase()) || data.userAlia.toLowerCase().includes(searchInput.toLowerCase()))
                return filterData.slice((currentPage-1)*pageSize,currentPage*pageSize)
            },
            total() {
                return this.tableData.length;
            }
        },
        methods:{
            getList() {
                getDeptList().then((res)=>{
                    let depArr = res.data.data;
                    if (!depArr){
                        this.$message.warning("请先添加部门！")
                        return;
                    }
                    this.deptList = depArr;
                    let m={};
                    this.deptList.forEach(p=>{
                        m[p.id]=p;
                    })
                    this.deptMaps=m;

                    this.dept_options=createDeptTree(depArr);
                }).then(()=>{
                    getUserList().then((res) => {
                        if(res.data && res.data.success){
                            this.tableData = [];
                            // console.log(res.data.data)
                            for (let i = 0; i < res.data.data.length; i++) {
                                let user = res.data.data[i];
                                this.tableData.push({
                                    userId: user.userId,
                                    userRole: user.roleId,
                                    userName: user.username,
                                    userAlia: user.name,
                                    userDepts: user.depts,
                                    userDeptNames:this.getDeptNames(user.depts)
                                })
                            }
                        }
                    })
                });


                getRoleList({
                    type: "BACK_ROLE"
                }).then((res) => {
                    if (res.data && res.data.code === 200) {

                        for (let i = 0; i < res.data.data.length; i++) {
                            if(res.data.data[i].roleAlias === "Administrator"){
                                res.data.data[i]["disabled"] = true;
                                this.role_options = res.data.data;
                                break;
                            }
                        }
                        // this.role_options = res.data.data;
                    }
                })
            },
            pageSizeChange(value) {
                this.page.currentPage = 1
                this.page.pageSize = value;
            },
            pageChange(value) {
                this.page.currentPage = value;
            },
            getDeptNames(csv){
                if(!csv) {
                    return "";
                }
                let deptArr=csv.split(",");
                let deptNames= deptArr.map(d=>{
                    return this.deptMaps[d]?this.deptMaps[d].name:""
                }).join(",")
                return deptNames;

            },
            formSubmit(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.dialogVisible = false;
                        if (this.submitState.state === "add") {
                            let userDeptsCSV = this.createCSVDepts([this.form.userDepts]);
                            addUser({
                                "username": this.form.userName,
                                "password": this.form.userPassword,
                                "name": this.form.userAlia,
                                "depts":userDeptsCSV,
                                "roleId": this.form.userRole
                            }).then((res) => {
                                if(res.data && res.data.success){
                                    this.$message.success("添加成功！")
                                    this.getList();
                                }else {
                                    this.$message.error("添加失败！")
                                }
                            })
                        }
                        else if (this.submitState.state === "update") {
                            let row = this.submitState.node;
                            let userDeptsCSV = this.createCSVDepts([this.form.userDepts]);
                            let data = {
                                "userId": row.userId,
                                "username": row.userName,
                                "name": this.form.userAlia,
                                "depts": userDeptsCSV,
                                "roleId": row.userRole
                            }
                            editUser(data).then((res) => {
                                if(res.data && res.data.success){
                                    this.$message.success("修改成功！")
                                    this.getList();
                                } else {
                                    this.$message.error("修改失败！")
                                }
                            })
                        }
                    } else {
                        return false;
                    }
                });
            },
            createCSVDepts(arr){
                return  arr.map(a=>{
                    let ind=a.length;
                    return a[ind-1]
                }).join(",");
            },
            handleAdd() {
                this.form.roleName = "";
                this.form.userAlia = ''
                this.form.roleAuthorities = [];
                this.form.checkAll = false;
                this.form.isIndeterminate = true;

                this.submitState.state = "add";
                this.dialogVisible = true;
            },
            handleUpdate(row) {
                this.submitState = {
                    state: "update",
                    node: row
                };
                this.form.userAlia = row.userAlia;
                this.form.userDepts = row.userDepts;
                // console.log(this.form.userDepts)
                this.dialogVisible = true;
            },
            createSelectedDepts(row){
                return createCascadDepValue(row.userDepts,this.deptList);//[[1],[1,2],[1,2,3]]  seleted 3 items
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleteUser({"userId": row.userId}).then((res) => {
                        if (res.data && res.data.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.getList();
                        } else {
                            this.$message.error("删除失败！")
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleResetPassword(row) {
                this.$confirm('此操作将重置该用户密码, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    resetUserPassword({
                        "userId": row.userId,
                        "newPassword": "123456",
                        "confirmPassword": "123456"
                    }).then((res) => {
                        if (res.data && res.data.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '重置成功，密码重置为123456'
                            });
                        } else {
                            this.$message.error("重置失败！")
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重置密码'
                    });
                });
            },
            handleChange(roles, row) {
                // let userDeptsCSV = this.createCSVDepts([row.userDepts]);
                let data = {
                    "userId": row.userId,
                    "username": row.userName,
                    "name": row.userAlia,
                    "depts": row.userDepts,
                    "roleId": roles
                }
                editUser(data).then((res) => {
                    if(res.data && res.data.success){
                        this.$message.success("修改成功！")
                    } else {
                        this.$message.error("修改失败！")
                    }
                    this.getList()
                })
            },
        },
        created() {
            this.getList();
        }
    }
</script>
